from flask import Blueprint, request, jsonify
from service.address import UserAddressService
from common.response import APIResponse

res = APIResponse()

# 创建蓝图
address_bp = Blueprint('address', __name__, url_prefix='/addresses')

@address_bp.route('/address', methods=['GET'])
def get_address():
    # 获取单个地址或用户的所有地址
    address_id = request.args.get('id')
    user_id = request.args.get('user_id')

    if address_id:
        return UserAddressService.get_address_by_id(address_id)
    elif user_id:
        return UserAddressService.get_addresses_by_user(user_id)
    else:
        return res.validate_error('请提供地址ID或用户ID')

@address_bp.route('/add', methods=['POST'])
def create_address():
    # 创建新地址
    data = request.get_json()
    if not data:
        return res.validate_error('请提供地址信息')
    return UserAddressService.create_address(data)

@address_bp.route('/update', methods=['POST'])  
def update_address():
    # 更新地址
    data = request.get_json()
    if not data or 'id' not in data:
        return res.validate_error('请提供地址ID')
    address_id = data.pop('id')
    return UserAddressService.update_address(address_id, data)

@address_bp.route('/delete', methods=['POST'])
def delete_address():
    # 删除地址
    data = request.get_json()
    if not data or 'id' not in data:
        return res.validate_error('请提供地址ID')
    address_id = data.pop('id')
    return UserAddressService.delete_address(address_id)
